package com.btashov.stringarray;

/**
 * @author Bahtiyar Tashov <btashov@gmail.com>
 */
/**
 * Py code
 * <pre><code>
 *  def removeDuplicates(string):
 *      result=[]
 *      seen=set()
 *  for char in string:
 *      if char not in seen:
 *      seen.add(char)
 *      result.append(char)
 *  return ''.join(result)
 * </code></pre>
 */
public class CharDuplicate {

    public String removeDuplicate(String str) {
        StringBuilder noDupes = new StringBuilder(str.length());
        for (int i = 0; i < str.length(); i++) {
            String si = str.substring(i, i + 1);
            if (noDupes.indexOf(si) == -1) {
                noDupes.append(si);
            }
        }
        return noDupes.toString();
    }

    public String removeDuplicateWithCheckArguments(String str) {
        if (str == null || str.isEmpty()) {
            throw new IllegalArgumentException("Illegal argument because of null or emptiness!");
        }

        StringBuilder noDupes = new StringBuilder(str.length());
        for (int i = 0; i < str.length(); i++) {
            String si = str.substring(i, i + 1);
            if (noDupes.indexOf(si) == -1) {
                noDupes.append(si);
            }
        }
        return noDupes.toString();
    }


    public static void removeDuplicates(char[] str) {
        int map = 0;
        for (int i = 0; i < str.length; i++) {
            if ((map & (1 << (str[i] - 'a'))) > 0) // duplicate detected
                str[i] = 0;
            else // add unique char as a bit '1' to the map
                map |= 1 << (str[i] - 'a');
        }
    }
}
